import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.Provider;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {
    private ServerSocket serverSocket=null;
    public TcpServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService service= Executors.newCachedThreadPool();
        while(true){
           Socket client= serverSocket.accept();
            service.submit(()->{
                try {
                        processConnection(client);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

            });
           /*Thread t=new Thread(()->{
               try {
                   processConnection(client);
               } catch (IOException e) {
                   e.printStackTrace();
               }
           });
            t.start();

            */
        }
    }

    private void processConnection(Socket client) throws IOException {
        System.out.printf("[%s :%d]客户端上线\n",client.getInetAddress(),client.getPort());
        try(InputStream inputStream=client.getInputStream();//TCP是全双工通信，既能读，也能写
            OutputStream outputStream=client.getOutputStream();
            PrintWriter printWriter=new PrintWriter(outputStream)){
            while(true){
                //1.读取请求并解析(为方便读，可使用Scanner)
                Scanner scanner=new Scanner(inputStream);
                if(!scanner.hasNext()){
                    //如果Scanner读不出下一个数据了，说明客户端关闭了连接，导致服务器读到了“末尾”
                    break;
                }
                //2.根据请求计算响应
                String request=scanner.next();
                String response=process(request);
                //3.把响应写回客户端
                printWriter.println(response);
                printWriter.flush();
                //4.打印日志
                System.out.printf("[%s :%d], rep=%s,reps=%s\n",client.getInetAddress(),client.getPort(),
                        request,response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            System.out.printf("[%s :%d]服务器下线\n",client.getInetAddress(),client.getPort());

            client.close();
        }

    }
    private String process(String response){
        return response;
    }

    public static void main(String[] args) throws IOException {
        TcpServer server=new TcpServer(9090);
        server.start();
    }
}
